#!/opt/sysroot64/usr/bin/python3.9
# coding:utf-8
import tornado
import tornado.ioloop
import tornado.web
import tornado.gen
from datetime import datetime
from .service import query_all_metrics
from prometheus_client.exposition import choose_encoder
port = 4030


class PingHandler(tornado.web.RequestHandler):
    def head(self):
        print('INFO', datetime.now(), "/ping Head.")
        self.write("OK")

    def get(self):
        print('INFO', datetime.now(), "/ping Get.")
        self.write("OK")

class MetricsHandler(tornado.web.RequestHandler):
    def get(self):
        print('INFO', datetime.now(), "/metrics Get.")
        data = query_all_metrics()
        encoder, content_type = choose_encoder(self.request.headers.get('accept'))
        self.set_header("Content-Type", content_type)
        self.write(data)


def make_app():
    return tornado.web.Application([
        (r"/ping?", PingHandler),
        (r"/metrics?", MetricsHandler)
    ])


def run(port=4030):
    app = make_app()
    app.listen(port)
    tornado.ioloop.IOLoop.current().start()

if __name__ == '__main__':
    run()
